var express = require('express')
var path = require('path')
var app = express()
var router = require('./router')
var jwt = require('./jwt')//jsonwebtoken

var bodyParser = require('body-parser')//解析post请求体
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

// 设置允许跨域访问
app.all('*', function (req, res, next) {
	res.header("Access-Control-Allow-Origin", "*");
	res.header('Access-Control-Allow-Methods', 'OPTIONS, PUT, GET, POST, DELETE');
	res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, Origin, Accept, Authorization");
	next();
});
// token添加口令
app.use(function (req, res, next) {
	// next()
	// console.log('123::'+req.headers.authorization)
	if (req.url == '/login' || req.url == '/preRegister' || req.url == '/register'|| req.url=='/preInvite') {
		next()
	} else {
		var token = req.headers.authorization
		// console.log(token)
		// token存在
		if (token && token != '') {
			jwt.getJwt(token, function (err, decode) {
				if (err) {// 伪造token
					res.send({ 'msgCode': -1 })
				} else {
					next()
				}
			})
		} else {
			res.send({ 'msgCode': -1 })
		}
	}
})
app.engine('html', require('express-art-template'))//epress-art-templata渲染引擎

app.use('/public/', express.static(path.join(__dirname, './public')))//开放静态资源
app.use('/node_modules/', express.static(path.join(__dirname, './node_modules')))

app.use(router)//导入路由

app.listen(3000, (err) => {
	console.log('running...')
})